package com.example.neteaseapplication.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import com.example.neteaseapplication.entity.Song;
import com.example.neteaseapplication.util.LocalMusicUtils;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class MusicService extends Service {

    private MediaPlayer mMediaPlayer;
    private Long mPrevMusicId = null;
    private List<Song> mSongList = new ArrayList<>();

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        mSongList = LocalMusicUtils.getmusic(getApplicationContext());
        return new MusicBinder();
    }

    public class MusicBinder extends Binder implements Serializable {
        public void start(Song song, Context context) {
            try {
                if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                    stop();
                    mMediaPlayer = new MediaPlayer();
                    mMediaPlayer.setDataSource(song.getPath());
                    mMediaPlayer.prepare();

                } else if (mMediaPlayer == null) {
                    mMediaPlayer = new MediaPlayer();
                    mMediaPlayer.setDataSource(song.getPath());
                    mMediaPlayer.prepare();
                } else if (mMediaPlayer != null && !mPrevMusicId.equals(song.getId())) {
                    stop();
                    mMediaPlayer = new MediaPlayer();
                    mMediaPlayer.setDataSource(song.getPath());
                    mMediaPlayer.prepare();
                }
                mPrevMusicId = song.getId();
                mMediaPlayer.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void pause() {
            if (mMediaPlayer.isPlaying() && mMediaPlayer != null) {
                mMediaPlayer.pause();
            }
        }

        public void stop() {
            mMediaPlayer.stop();//停止
            mMediaPlayer.reset();//重置
            mMediaPlayer.release();//释放资源
            mMediaPlayer = null;
        }
        public MediaPlayer getMediaPlayer(){
            return mMediaPlayer;
        }
    }
}
